#include "InetAddress.h"
#include <string.h>
#include <arpa/inet.h>


InetAddress::InetAddress(uint16_t port, bool loopBackOnly)
{
    memset(&_addr, 0, sizeof(_addr));
    _addr.sin_family = AF_INET;
    in_addr_t ip = loopBackOnly ? INADDR_LOOPBACK : INADDR_ANY;
    _addr.sin_addr.s_addr = ::htonl(ip);
    _addr.sin_port = ::htons(port);
}
InetAddress::InetAddress(const string &ip, uint16_t port)
{
    memset(&_addr, 0, sizeof(_addr));
    _addr.sin_family = AF_INET;
    _addr.sin_port = ::htons(port);
    if(::inet_pton(AF_INET, ip.c_str(), &_addr.sin_addr) <= 0)
    {
        perror("InetAddress::InetAddress inet_pton");
        std::exit(1);
    }
}

string InetAddress::ip() const
{
    char buf[INET_ADDRSTRLEN] = {0};
    ::inet_ntop(AF_INET, &_addr.sin_addr, buf, sizeof(buf));
    return buf;
}
uint16_t InetAddress::port() const
{
    return ntohs(_addr.sin_port);
}
const struct sockaddr *InetAddress::getAddrPtr() const
{
    return reinterpret_cast<const struct sockaddr*>(&_addr);
}
struct sockaddr_in *InetAddress::getAddrinPtr()
{
    return &_addr;
}
